Swift Data
Swift Data for Data Management
Swift Data (formerly Core Data) allows you to efficiently manage persistent data in your app. It's perfect for saving, fetching, and modifying your app’s data.
Swift Data Example
To save data using Swift Data, you’ll need to set up your data model and integrate it into your SwiftUI views.
Here’s how to create a basic data model and fetch the data in SwiftUI:
swift
import SwiftUI import CoreData @main struct MyApp: App { let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) } } } struct ContentView: View { @FetchRequest( entity: Item.entity(), sortDescriptors: [] ) var items: FetchedResults<Item> var body: some View { List { ForEach(items) { item in Text(item.name ?? "Unknown") } } } }
You can set up PersistenceController
to handle your CoreData
stack and manage saving and fetching data behind the scenes.